<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>品种信息</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
              @handleEvent="pageHandleEvent"
            >
              <template v-slot:form-tsProjectName="scope">
                <el-input
                  v-model="formInfo.data.tsProjectName"
                  type="input"
                  placeholder="请选择项目"
                >
                  <template #append>
                    <el-icon @click="changeData(scope.$index)"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
            </PageForm>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>明细信息</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-addProduct>
                <el-button @click="addProduct">新增单品</el-button>
              </template>
              <template v-slot:filter-breedProduct>
                <el-button @click="breedProduct">新增品种</el-button>
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :checkBox="false"
                  :tab-index="false"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isRowClickSelect="true"
                  :isDynamic="true"
                  :spanMethod="spanMethod"
                  @handleEvent="handleEvent"
                >
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>
    <!-- 添加项目 -->
    <SelectProject
      v-if="selectProjectObj.visible"
      v-model:show-dialog="selectProjectObj.visible"
      :query="selectProjectObj.query"
      :api="selectProjectObj.api"
      :check-box="false"
      :highlightRow="true"
      @callback="callBackAsset"
    />
    <!-- 添加单品 -->
    <NewSelectProduct
      v-if="productInfo.visible"
      v-model:showDialog="productInfo.visible"
      v-model:query="productInfo.query.queryMap"
      :api="productInfo.api"
      :query-params="productInfo.query.queryParams"
      :tableKey="productInfo.tableKey"
      :showEditQty="false"
      @callback="selectProduct"
    />
    <!-- 添加品种 -->
    <SelectBreed
      v-if="selectBreedObj.visible"
      v-model:show-dialog="selectBreedObj.visible"
      :query="selectBreedObj.query"
      :api="selectBreedObj.api"
      :check-box="true"
      :highlightRow="true"
      @callback="callBackBreed"
    />
  </div>
</template>

<script setup name="cmProjectModify">
import { getProductCustomizeList } from '@/api/core.js'
import {
  postMappingProductProjects,
  getTripartiteSystemProject,
  getProductVarieties,
  updateMappingProductProjects,
  getMappingProductProjectById,
} from '@/api/cmPreMgt'
import moment from 'moment'
const SelectProject = defineAsyncComponent(() => import('./selectProject'))
const SelectBreed = defineAsyncComponent(() => import('./selectBreed'))
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'id'])
const emits = defineEmits()
import _ from 'lodash'

const formRefs = ref([])
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    tsSystemCode: 'LIS',
    tsProjectId: '',
    tsProjectName: '',
    tsProjectCode: '',
    deptId: '',
    executeStartDate: moment(new Date()).format('YYYY-MM-DD'),
  },
  fieldList: [
    {
      label: '对接系统',
      value: 'tsSystemCode',
      type: 'select-model',
      code: 'client_id',
      required: true,
      event: 'tsSystemChange',
    },
    {
      label: '项目名称',
      value: 'tsProjectName',
      type: 'slot',
    },
    {
      label: '项目编码',
      value: 'tsProjectCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '执行开始日期',
      value: 'executeStartDate',
      type: 'date',
      require: true,
    },
    {
      label: '执行截止日期',
      value: 'executeEndDate',
      type: 'date',
      labelTip: '默认截止日期为2099年12月31日',
    },
  ],
  rules: {
    tsSystemCode: [
      {
        required: true,
        message: '请选择对接系统',
        trigger: 'change',
      },
    ],
    tsProjectName: [
      {
        required: true,
        message: '请选择项目',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'breedProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '序号', value: 'index', width: '40' },
    { label: '产品类型', value: 'varietiesTypeValue' },
    { label: '品种名称', value: 'varietiesName' },
    { label: '产品编码', value: 'productCode' },
    { label: '产品名称', value: 'commonName' },
    { label: '厂家', value: 'brandName' },
    { label: '规格', value: 'standard' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: breedRemoveProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
//选择产品相关
const productInfo = ref({
  api: getProductCustomizeList,
  visible: false,
  tableKey:
    'exceptActualSelectProduct-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      varietiesName: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
        ignoreEmptyValue: false,
      },
    },
    queryParams: {
      tsProjectNotIn: '',
    },
  },
})
const selectProjectObj = ref({
  visible: false,
  api: getTripartiteSystemProject,
  query: {
    tsSystemCode: '',
  },
})
const selectBreedObj = ref({
  visible: false,
  api: getProductVarieties,
  query: {
    varietiesIdNotIn: '',
    tsProjectNotIn: '',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveAsset = computed(() => {
  return tableInfo.value.selections.length
})
watch(
  () => props.id,
  (val) => {
    if (!val) return
    getMappingProductProjectById(val).then((res) => {
      if (res.success) {
        formInfo.value.data = res.data
        res.data.details.forEach((item) => {
          if (item.varietiesType === 1) {
            item.mergeTableKey = 'danpin' + item.id
          } else if (item.varietiesType === 2) {
            item.mergeTableKey = 'pinzhong' + item.varietiesId
          }
        })
        tableInfo.value.data = res.data.details
      }
    })
  },
  {
    immediate: true,
  }
)

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})

function pageHandleEvent(event, data) {
  if (event === 'tsSystemChange') {
    tableInfo.value.data = []
    closeProjectInfo()
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function spanMethod({ row, column, rowIndex, columnIndex }) {
  let keys = ['index', 'mergeTableKey', 'varietiesName', '', '', '', '']
  const afterIndexs = [7]
  if (afterIndexs.includes(columnIndex)) {
    keys[columnIndex] = 'index'
  } else {
    keys = ['index', 'mergeTableKey', 'varietiesName']
  }
  // 注意:字段列表要按表格排列的顺序排列,如果后续字段不再需要进行行合并,可以省略后面的字段,如果中间某字段要跳过合并,要用空字符串顶位
  return proxy.$fn.spanMethod(tableInfo.value.data, keys, rowIndex, columnIndex)
}
function changeData(index) {
  selectProjectObj.value.query.tsSystemCode = formInfo.value.data.tsSystemCode
  //打开使用部门弹窗
  selectProjectObj.value.visible = true
}
function callBackAsset(row) {
  //使用部门返回
  if (row && row.id) {
    formInfo.value.data.tsProjectId = row.id
    formInfo.value.data.tsProjectName = row.tsProjectName
    formInfo.value.data.tsProjectCode = row.tsProjectCode
    formInfo.value.data.deptId = row.deptId
  } else {
    closeProjectInfo()
  }
}
function closeProjectInfo() {
  formInfo.value.data.tsProjectId = ''
  formInfo.value.data.tsProjectName = ''
  formInfo.value.data.tsProjectCode = ''
  formInfo.value.data.deptId = ''
}
//选择产品
function addProduct() {
  productInfo.value.query.queryMap.id.value = null
  productInfo.value.query.queryParams.tsProjectNotIn =
    formInfo.value.data.tsProjectId
  if (tableInfo.value.data.length) {
    productInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => {
        if (item.productId) {
          return item.productId
        }
      })
      .toString()
  }
  productInfo.value.visible = true
}
//产品回调
function selectProduct(rows) {
  if (rows) {
    rows.forEach((item, index) => {
      item.varietiesTypeValue = '单品'
      // 1-单品 2-品种
      item.varietiesType = 1
      item.mergeTableKey = 'danpin' + item.id
    })
    tableInfo.value.data = rows.concat(tableInfo.value.data)
    updateTableIndex(tableInfo.value.data)
  }
}
function breedProduct(index) {
  selectBreedObj.value.query.varietiesIdNotIn = null
  selectBreedObj.value.query.tsProjectNotIn = formInfo.value.data.tsProjectId
  if (tableInfo.value.data.length) {
    const varietiesIdArr = []
    tableInfo.value.data.forEach((item) => {
      if (item.varietiesId && item.varietiesType === 2) {
        varietiesIdArr.push(item.varietiesId)
      }
    })
    const newArr = [...new Set(varietiesIdArr)]
    selectBreedObj.value.query.varietiesIdNotIn = newArr.toString()
  }
  selectBreedObj.value.visible = true
}
// 品种回调
function callBackBreed(rows) {
  if (!rows || !rows.length) return
  let tempArr = _.values(_.groupBy(rows, 'varietiesId'))
  console.log(tempArr)
  const newArr = []
  tempArr.forEach((item, index) => {
    item.forEach((item2) => {
      item2.varietiesTypeValue = '品种'
      // 1-单品 2-品种
      item2.varietiesType = 2
      item2.mergeTableKey = 'pinzhong' + item2.varietiesId
      newArr.unshift(item2)
    })
  })
  console.log(newArr)
  tableInfo.value.data = newArr.concat(tableInfo.value.data)
  console.log(tableInfo.value.data)
  updateTableIndex(tableInfo.value.data)
}
//删除产品
function breedRemoveProduct(row) {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      tableInfo.value.data = tableInfo.value.data.filter(
        (item) => item.index !== row.index
      )
      updateTableIndex(tableInfo.value.data)
    })
}
function updateTableIndex(data = []) {
  console.log(data)
  let tempArr = _.values(_.groupBy(data, 'mergeTableKey'))
  console.log(tempArr)
  tableInfo.value.data = []
  tempArr.forEach((item, index) => {
    item.forEach((item2) => {
      item2.index = index + 1
      tableInfo.value.data.push(item2)
    })
  })
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.value.data
    const data = formInfo.value.data
    if (!details.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }
    const arr = []
    details.forEach((item) => {
      arr.push({
        productId: item.productId,
        varietiesId: item.varietiesId,
        varietiesType: item.varietiesType,
      })
    })
    data.details = arr
    const api = data.id
      ? updateMappingProductProjects
      : postMappingProductProjects
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
</script>

<style scoped lang="scss"></style>
